package com.jy.admin.jobs;

import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.base.services.oss.OSSService;
import com.fqgj.common.api.Page;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.StringUtils;
import com.jy.admin.config.ApolloConfigUtil;
import com.jy.admin.db.dao.OpdCsvExpandDao;
import com.jy.admin.db.dao.OpdUploadRecordDao;
import com.jy.admin.db.entity.OpdCsvExpandEntity;
import com.jy.admin.db.entity.OpdUploadRecordEntity;
import com.jy.admin.enums.OpdUploadStatusEnum;
import com.robert.vesta.util.IdUtils;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ocr.v20181119.OcrClient;
import com.tencentcloudapi.ocr.v20181119.models.EnglishOCRRequest;
import com.tencentcloudapi.ocr.v20181119.models.GeneralAccurateOCRRequest;
import com.tencentcloudapi.ocr.v20181119.models.GeneralBasicOCRRequest;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2021/11/28
 * Time: 9:35 下午
 */
@Service
public class DndCheckJob {

    private static final Logger LOGGER = LoggerFactory.getLogger(DndCheckJob.class);

    @NacosValue(value = "${chrome.driver.path:/home/java/dc-ms/chromedriver}", autoRefreshed = true)
    private String chromeDriverPath;

    @Autowired
    private OSSService ossService;

    @Autowired
    private ApolloConfigUtil configUtil;

    @Autowired
    private OpdUploadRecordDao opdUploadRecordDao;


    @Autowired
    private OpdCsvExpandDao opdCsvExpandDao;

//    @Scheduled(fixedDelay = 1000L * 20)
    public void run() {

        if (!configUtil.getDndCheck()) {
            LOGGER.info("===switch not open ==");
            return;
        }


        Page page = new Page();
        page.setPageSize(100);
        List<OpdUploadRecordEntity> dndCheckedListByStatus = opdUploadRecordDao.getDndCheckedListByStatus(OpdUploadStatusEnum.FINISHED.getStatus(), 0, page);
        if (CollectionUtils.isEmpty(dndCheckedListByStatus)) {
            LOGGER.info("=== need check dnd size ==0 ==");
            return;
        }

        LOGGER.info("=== need check dnd  ==,size:{}", dndCheckedListByStatus.size());

        dndCheckedListByStatus.forEach(opdUploadRecordEntity -> {

            int pageSize = 1000;
            int currentPage = 1;
            Page page1 = new Page();
            page1.setCurrentPage(currentPage);
            page1.setPageSize(pageSize);

            List<OpdCsvExpandEntity> listByDataNoPageFirst = opdCsvExpandDao.getNeedCheckDndListByDataNo(opdUploadRecordEntity.getDataNo(), page1);
            if (CollectionUtils.isEmpty(listByDataNoPageFirst)) {
                opdUploadRecordEntity.setDndChecked(1);
                int dndCntByDataNo = opdCsvExpandDao.getDndCntByDataNo(opdUploadRecordEntity.getDataNo());
                opdUploadRecordEntity.setActiveCnt(opdUploadRecordEntity.getTotalCnt() - dndCntByDataNo);
                opdUploadRecordDao.updateByPrimaryKey(opdUploadRecordEntity);
            }

            while (true) {
                List<OpdCsvExpandEntity> listByDataNo = opdCsvExpandDao.getNeedCheckDndListByDataNo(opdUploadRecordEntity.getDataNo(), page1);
                if (CollectionUtils.isEmpty(listByDataNo)) {
                    LOGGER.info("=== listByDataNo size ==0 ==");
                    return;
                }
                LOGGER.info("=== listByDataNo size:{} ==", listByDataNo.size());

                List<String> allMobiles = new ArrayList<>();
                listByDataNo.forEach(opdCsvExpandEntity -> {
                    if (StringUtils.isEmpty(opdCsvExpandEntity.getMobile())) {
                        return;
                    }
                    LOGGER.info("=== mobile detail  ==,dataNo:{},mobile:{}", opdCsvExpandEntity.getDataNo(), opdCsvExpandEntity.getMobile());
                    allMobiles.add(opdCsvExpandEntity.getMobile());
                });

                if (CollectionUtils.isEmpty(allMobiles)) {
                    continue;
                }
                try {
                    //找到DND的手机号码
                    List<String> dndMobileList = getDNDMobileList(allMobiles);
                    if (CollectionUtils.isEmpty(dndMobileList)) {
                        opdCsvExpandDao.updateDndStatus(opdUploadRecordEntity.getMerchantCode(), opdUploadRecordEntity.getDataNo(), allMobiles, 0);
                    } else {
                        opdCsvExpandDao.updateDndStatus(opdUploadRecordEntity.getMerchantCode(), opdUploadRecordEntity.getDataNo(), allMobiles, 0);
                        opdCsvExpandDao.updateDndStatus(opdUploadRecordEntity.getMerchantCode(), opdUploadRecordEntity.getDataNo(), dndMobileList, 1);
                    }
                    if (listByDataNo.size() < pageSize) {
                        break;
                    }

                    currentPage++;
                    page1.setCurrentPage(currentPage);
                } catch (Exception e) {
                    LOGGER.error("== get dndMobileList error ==", e);
                }


            }


        });

    }


    public List<String> getDNDMobileList(List<String> needCheckMobiles) throws Exception {


//        System.setProperty("webdriver.chrome.driver", "/Users/yujianfu/Downloads/chromedriver");
        System.setProperty("webdriver.chrome.driver", chromeDriverPath);

        // Initialize browser
        System.setProperty("webdriver.chrome.whitelistedIps", "");
        ChromeOptions chromeOptions = new ChromeOptions();
        //关闭窗口
        chromeOptions.addArguments("--headless");
        chromeOptions.addArguments("--window-size=2560,1980");
        chromeOptions.addArguments("--disable-dev-shm-usage");

        //无痕浏览
        chromeOptions.addArguments("--incognito");
        chromeOptions.addArguments("--whitelisted-ips");
        chromeOptions.addArguments("--no-sandbox");
        WebDriver driver = new ChromeDriver(chromeOptions);
        driver.get("http://dndsearch.in/index.php");

        LOGGER.info("== 获取验证码 开始 ==,title:{}", driver.getTitle());
//        x=1105&y=670&w=70&h=30

        getFullScreenShot(driver, "A");
        String verifyCode = getVerifyCode(driver, 1105, 675,
                62, 22);

//        String verifyCode = getVerifyCode(driver,2210, 1350,
//                130, 45);

        LOGGER.info("== 获取验证码 结束 ==,code:{}", verifyCode);

        List<String> res = null;
        try {
            WebElement allMobiles = driver.findElement(By.xpath("/html/body/div[1]/div/div[3]/div[2]/div[2]/div[2]/div/form/div[1]/textarea"));

            String inputValue = "";
            for (String mobile : needCheckMobiles) {
                inputValue += mobile + "\n";
            }
            LOGGER.info("== 输入手机号码 ==,size:{}", needCheckMobiles.size());
            allMobiles.sendKeys(inputValue);

            WebElement captchaInput = driver.findElement(By.xpath("/html/body/div[1]/div/div[3]/div[2]/div[2]/div[2]/div/form/div[2]/input[2]"));
            LOGGER.info("== 输入验证码 ==");
            captchaInput.sendKeys(verifyCode);

            ///html/body/div[1]/div/div[3]/div[2]/div[2]/div[2]/div/form/div[3]/input[2]
            WebElement submitButton = driver.findElement(By.xpath("/html/body/div[1]/div/div[3]/div[2]/div[2]/div[2]/div/form/div[3]/input[2]"));
            LOGGER.info("== 点击按钮 ==");
            submitButton.click();

            LOGGER.info("== 跳转到结果页，等待结果中 ==");
            getFullScreenShot(driver, "B");

            LOGGER.info("== 跳转到结果页，等待结果中 等待5秒结束 获取屏幕截图结束==");
            new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("/html/body/div[1]/div/div[3]/div[2]/div[1]/div[2]/div/div/textarea[1]")));
            LOGGER.info("== 已经到结果页 ==,title:{}", driver.getTitle());

            WebElement dndMobilesTextArea = driver.findElement(By.xpath("/html/body/div[1]/div/div[3]/div[2]/div[1]/div[2]/div/div/textarea[1]"));
            res = Arrays.asList(dndMobilesTextArea.getText().split("\n"));
            if (res.size() == 1) {
                if (StringUtils.isEmpty(res.get(0).trim())) {
                    res = new ArrayList<>();
                }
            }
            LOGGER.info("== 已经到结果页，获取到DND号码 ==，size:{}", res.size());
        } catch (Exception e) {
            LOGGER.error("== dnd check exception ==", e);
        }
        driver.quit();

        LOGGER.info("== 关闭driver==");
        return res;
    }

    public String getVerifyCode(WebDriver driver, int x, int y, int width, int height) {
        try {

            LOGGER.info("== getVerifyCode ==,x:{},y:{},w:{},h:{}", x, y, width, height);
            File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
            LOGGER.info("== 网页截图 ==");

            BufferedImage fullScreen = ImageIO.read(screenshot);
            BufferedImage logoImage = fullScreen.getSubimage(x, y, width, height);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(logoImage, "png", os);                          // Passing: ​(RenderedImage im, String formatName, OutputStream output)
            InputStream is = new ByteArrayInputStream(os.toByteArray());
            LOGGER.info("== 网页截图 InputStream success==");

            String fileName = "dnd" + "/" + IdUtils.genId() + ".png";
            LOGGER.info("== getVerifyCode ==,fileName:{}", fileName);
            ossService.uploadFile(configUtil.getBucketName(), is, is.available(), fileName);
            String fullUrl = configUtil.getOssBaseUrl() + "/" + fileName;

            LOGGER.info("== full-url ==,url:{}", fullUrl);

            Credential cred = new Credential("AKIDxiCQN3SaR2LN8cpkOlsjKfkY4JHyPYQ1", "MRFmulKdeOs51g4B1Zqqa3F9m9E2YonV");
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("ocr.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            OcrClient client = new OcrClient(cred, "ap-hongkong", clientProfile);
            EnglishOCRRequest req = new EnglishOCRRequest();
            req.setImageUrl(fullUrl);
            HashMap<String, String> resMap = new HashMap<>();
            client.EnglishOCR(req).toMap(resMap, "");
            return resMap.get("TextDetections.0.DetectedText");
        } catch (Exception e) {
            System.out.println(e.toString());
        }

        return null;
    }

    public String getFullScreenShot(WebDriver driver, String pageName) {
        if (!configUtil.getdndCheckPage()) {
            LOGGER.info("== 网页全截图full == switch false");
            return null;
        }
        try {

            File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
            LOGGER.info("== 网页截图 full ==");

            BufferedImage fullScreen = ImageIO.read(screenshot);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(fullScreen, "png", os);                          // Passing: ​(RenderedImage im, String formatName, OutputStream output)
            InputStream is = new ByteArrayInputStream(os.toByteArray());
            LOGGER.info("== 网页截图full InputStream success==");

            String fileName = "dnd" + "/" + IdUtils.genId() + "--" + pageName + ".png";
            ossService.uploadFile(configUtil.getBucketName(), is, is.available(), fileName);
            String fullUrl = configUtil.getOssBaseUrl() + "/" + fileName;

            LOGGER.info("==fullfullfullfull full-url ==,url:{}", fullUrl);
        } catch (Exception e) {
            System.out.println(e.toString());
        }

        return null;
    }

    public static void main(String[] args) {
        String re = "9266444011\n" +
                "9266635100\n" +
                "9267941689\n" +
                "9268459434\n" +
                "9269004418\n" +
                "9266475008\n" +
                "9266664012";

        String[] split = re.split("\n");

        System.err.println(11);
    }


}
